package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPReceiveDemo1 {
    public static void main(String[] args) {
        try {
            //创建Socket
            DatagramSocket datagramSocket = new DatagramSocket(8888);

            //准备数据包，用于接收发送过来的数据
            byte[] bytes = new byte[1024];      // 用于存放发送端发送过来的字节数据
            DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);

            //获取数据包
            datagramSocket.receive(datagramPacket);     // receive是一个阻塞式方法

            //查看发送端发送过来的信息
            String ipAddress = datagramPacket.getAddress().getHostAddress();
            int port = datagramPacket.getPort();        // 获取发送端程序的端口
            byte[] content = datagramPacket.getData();  // 获取发送端发送过来的数据
            System.out.println(ipAddress + ":" + port + "==>" + new String(content,0, datagramPacket.getLength()));

            //关闭网络资源
            datagramSocket.close();



        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
